import java.util.Arrays;

public class MergeSort {
    //辅助数组
    static int[] temp;

    public static void main(String[] args) {
        int[] nums = {1, 3, 4, 5, 2, 6, 8, 7};
        temp = new int[nums.length];
        mergeSort(nums, 0, nums.length - 1);
        System.out.println(Arrays.toString(nums));
    }

    public static void mergeSort(int[] nums, int left, int right) {
        if (left < right) {
            int mid = left + (right - left) / 2;
            mergeSort(nums, left, mid);
            mergeSort(nums, mid + 1, right);
            merge(nums, left, mid, right);
        }
    }

    public static void merge(int[] nums, int left, int mid, int right) {
        int i = left;
        int j = mid + 1;
        int k = left;
        while (i <= mid && j <= right) {
            if (nums[i] <= nums[j]) {
                temp[k++] = nums[i++];
            } else {
                temp[k++] = nums[j++];
                //res += mid-i+1;
            }
        }
        while (i <= mid) {
            temp[k++] = nums[i++];
        }
        while (j <= right) {
            temp[k++] = nums[j++];
        }
        //拷贝回原来数组
        for (int t = left; t <= right; t++) {
            nums[t] = temp[t];
        }

    }

}
